/*
 * @Author: szx
 * @Date: 2022-02-23 12:58:15
 * @LastEditTime: 2022-02-23 13:05:33
 * @Description:
 * @FilePath: \leetcode\100-199\160\160_2.js
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
    let cur1 = headA;
    let len1 = 0;
    while (cur1) {
        cur1 = cur1.next;
        len1++;
    }
    let cur2 = headB;
    let len2 = 0;
    while (cur2) {
        cur2 = cur2.next;
        len2++;
    }
    cur1 = headA;
    cur2 = headB;
    if (len1 < len2) {
        [len1, len2] = [len2, len1];
        [cur1, cur2] = [cur2, cur1];
    }
    for (let i = 0; i < len1 - len2; i++) cur1 = cur1.next;

    while (cur1 != cur2) {
        cur1 = cur1.next;
        cur2 = cur2.next;
    }
    return cur1;
};

// 神奇拼接法则，很好。
var getIntersectionNode = function (headA, headB) {
    let p1 = headA,
        p2 = headB;
    while (p1 != p2) {
        p1 = p1 === null ? headB : p1.next;
        p2 = p2 === null ? headA : p2.next;
    }
    return p1;
};
